/* 

将多维数组转化为一维数组。

示例:
[1, [2, [3, [4, 5]]], 6] -> [1, 2, 3, 4, 5, 6]

*/


// 利用闭包
/* let flatten = (arr) => {
    let result = [];

    let flat = (arr) => {
        for (let i = 0, len = arr.length; i < len; i++) {
            const item = arr[i];
            if (Array.isArray(item)) {
                flat(item)
            } else {
                result.push(item);
            }
        }
    }

    flat(arr);
    return result;
} */

// 利用原生函数Array.prototype.flat()
/* let flatten = (arr) => {
    let deep = 1;

    let resolveDeep = (arr) => {
        for (let i = 0, len = arr.length; i < len; i++) {
            const item = arr[i];
            if (Array.isArray(item)) {
                deep++;
                resolveDeep(item)
            }
        }
    }

    resolveDeep(arr)

    return arr.flat(deep);
} */

// 利用Array.prototype.reduce()
const flatten = (nestedList) => nestedList.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), [])

var arr = [1, [2, [3, [4, 5]]], 6];

console.log(flatten(arr));

// 利用yield
function* iterTree(tree) {
    if (Array.isArray(tree)) {
        for (let i = 0; i < tree.length; i++) {
            yield* iterTree(tree[i]);
        }
    } else {
        yield tree;
    }
}

const tree = ['a', ['b', 'c'],
    ['d', 'e']
];

[...iterTree(tree)] // ["a", "b", "c", "d", "e"]